<template>
  <View class="container">
    <new-year-task-pop ref="newYearTask"></new-year-task-pop>
    <View class="test-progress">
      <View class="progress-top">
        <Text class="progress-label">测试进度</Text>
        <Text class="progress-value">{{ currentQuestionIndex + 1 }}/{{ allQuestion.length }}</Text>
      </View>
      <View class="progress-bottom">
        <View class="progress" :style="{ width: progressValue }"></View>
      </View>
    </View>
    <View class="content">
      <image mode="widthFix" class="up-content-box" :src="`${imgBasePath}tcm/up-content-box.png`"></image>
      <image mode="widthFix" class="lower-content-box" :src="`${imgBasePath}tcm/lower-content-box.png`"></image>
      <View class="left-line"></View>
      <View class="right-line"></View>
      <View class="title">第 {{ currentQuestionIndex + 1 }} 题</View>
      <View class="desc">{{ currentQuestion.question }}</View>
      <View class="button" v-for="(item, index) in currentQuestion.options" :key="index"
            :class="{ 'select-button': currentQuestion.selectedAnswer === item.name }" @click="onSelect(item, index)">{{
          item.label
        }}
      </View>
    </View>
    <View class="footer">
      <View class="question" @click="onPrevQuestion" v-if="!isFirstQuestion">
        <image class="left-arrow" :src="`${imgBasePath}tcm/left-arrow.png`"></image>
        <Text>上一题</Text>
      </View>
      <View v-else></View>
      <!-- <View class="question" @click="onNextQuestion" v-if="!isLastQuestion">
        <Text>下一题</Text>
        <image class="right-arrow" :src="`${imgBasePath}tcm/right-arrow.png`"></image>
      </View> -->
      <View v-if="isLastQuestion && currentQuestion.selectedAnswer" class="view-result" @click="toViewResult">
        查看结果
      </View>
    </View>
    <View class="mask" v-if="showAnalyseLoading">
      <View class="loading-wrap">
        <image class="loading" mode="widthFix" :src="`${imgBasePath}tcm/result-loading.gif`"></image>
        <View class="loading-text">分析中，请您稍候</View>
      </View>
    </View>
  </View>
</template>
<script>
import {imgBasePath, trackingHost} from "@/common/config";
import NewYearTaskPop from "@/components/new-year-task-pop/new-year-task-pop.vue";

export default {
  name: "answer",
  components: {NewYearTaskPop},
  data() {
    return {
      answers: [{text: "没有"}, {text: "很少"}, {text: "有时"}, {text: "经常"}, {text: "经常"}, {text: "总是"}],
      selectAnswerIndex: null,
      currentQuestionIndex: 0,
      allQuestion: [],
      recordId: null,
      startTime: Date.parse(new Date()),
      storeId: null,
      imgBasePath,
      isAnswering: false,
      showAnalyseLoading: false,
    }
  },
  onLoad(params) {
    const {recordId, storeId, invitorCode} = params;
    this.recordId = recordId;
    this.storeId = +storeId;
    this.invitorCode = invitorCode;
  },
  onShareAppMessage(res) {
    return {
      title: "快！亿万苍生，人分九种，来测测你的中医体质！",
      path: `pages/physiqueTest/index?storeId=${this.storeId}&source=2&invitorCode=${this.invitorCode}`,
      imageUrl: `${imgBasePath}tcm/share-image.png`,
    }
  },
  onUnload() {
    const endTime = Date.parse(new Date());
    this.tcmQA(endTime);
  },
  computed: {
    currentQuestion() {
      return this.allQuestion[this.currentQuestionIndex] || {};
    },
    isFirstQuestion() {
      return !this.currentQuestionIndex;
    },
    isLastQuestion() {
      return this.currentQuestionIndex === this.allQuestion.length - 1;
    },
    progressValue() {
      const AnsweredNumber = this.allQuestion.filter(item => !!item.selectedAnswer).length;
      const total = this.allQuestion.length;
      const value = Math.floor(AnsweredNumber / (total) * 100);
      return `${value}%`
    },
  },
  methods: {
    onSelect(item, index) {
      // this.selectAnswerIndex = index;
      this.saveConstitution(item);
    },
    onPrevQuestion() {
      this.currentQuestionIndex = this.currentQuestionIndex - 1;
    },
    // onNextQuestion() {
    //   this.currentQuestionIndex = this.currentQuestionIndex + 1;
    // },
    getAnswer() {
      this.$request("marketing-tcm/constitution/get-qa-pool", {method: "GET", showLoading: true})
          .then(res => {
            this.allQuestion = res;
          })
          .catch(error => {
          })
    },
    saveConstitution({name}) {
      if (this.isAnswering) return;
      this.isAnswering = true;
      const {allQuestion, currentQuestionIndex} = this;
      allQuestion[currentQuestionIndex]["selectedAnswer"] = name;
      this.allQuestion = JSON.parse(JSON.stringify(allQuestion));

      const feedbacks = allQuestion.filter((item) => !!item.selectedAnswer).map(item => {
        return {
          option: item.selectedAnswer,
          qaId: item.id
        }
      });

      const params = {
        feedbackStatus: feedbacks.length === allQuestion.length ? "Finish" : "Doing",
        feedbacks,
        recordId: this.recordId
      }
      this.$request("marketing-tcm/constitution/save-constitution", {params})
          .then(res => {
            if (currentQuestionIndex < allQuestion.length - 1) {
              this.currentQuestionIndex = this.currentQuestionIndex + 1;
            }
          }).catch(() => {
        allQuestion[currentQuestionIndex]["selectedAnswer"] = undefined;
        this.allQuestion = JSON.parse(JSON.stringify(allQuestion));
      }).finally(() => {
        this.isAnswering = false;
      })
    },
    toViewResult() {
      if (this.currentQuestion.selectedAnswer) {
        if (uni.getStorageSync("taskId") === 5) {
          this.taskComplete();
        }
        this.showAnalyseLoading = true;
        setTimeout(() => {
          this.showAnalyseLoading = false;
          uni.redirectTo({
            url: `/pages/physiqueTest/symptomIntroduction?recordId=${this.recordId}&storeId=${this.storeId}&invitorCode=${this.invitorCode}`
          });
        }, 3000);
      }
    },
    //任务完成上报
    async taskComplete() {
      let data = {
        taskId: uni.getStorageSync("taskId"),
        hasSendReward: 1
      }
      await this.$javaCircle.doRequest("post", 'vs/newbie/doNewBieTask', data, 'json')
      uni.setStorageSync("taskId", false)
      await this.$refs.newYearTask.show()
    },
    tcmQA(endTime) {
      const st = (endTime - this.startTime) / 1000;
      const {unionid, openid} = uni.getStorageSync("userInfo")
      const params = {
        oid: openid,
        uid: unionid,
        sid: this.storeId,
        event: "sessionTime",
        page: "tcmQA",
        ts: Date.parse(new Date()) / 1000,
        st,
        rid: this.recordId,
      }
      this.$request("event-tracking/user", {host: trackingHost, params})
          .catch(() => {
          })
    },
  },
  created() {
    this.getAnswer();
  },
}
</script>
<style lang="scss" scoped>
.container {
  position: relative;
  min-height: 100vh;
  background-color: #EFE8D6;
  padding: 0 24rpx;
  padding-top: 40rpx;
  padding-bottom: 130rpx;
  font-family: "PingFangSC-Semibold";

  .mask {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.50);

    .loading-wrap {
      width: 420rpx;
      background: #FFFFFF;
      border-radius: 24rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 74rpx;
      padding-bottom: 62rpx;

      .loading {
        width: 200rpx;
        height: 200rpx;
      }

      .loading-text {
        font-family: " PingFangSC-Semibold";
        margin-top: 46rpx;
        font-size: 42rpx;
        color: #333333;
        text-align: center;
        font-weight: 600;
      }
    }
  }

  .test-progress {
    margin-bottom: 85rpx;

    .progress-top {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 18rpx;
      font-size: 24rpx;
      color: #333333;
      font-weight: 600;
    }

    .progress-bottom {
      height: 18rpx;
      padding: 3rpx;
      background: #F8F5EE;

      .progress {
        height: 12rpx;
        // width: 50%;
        background-color: #C7A27C;
      }
    }
  }

  .content {
    position: relative;
    text-align: center;
    padding: 35rpx 45rpx 65rpx;
    background-color: #F8F5EE;

    .up-content-box {
      position: absolute;
      width: 100%;
      top: -25rpx;
      left: 0;
    }

    .lower-content-box {
      position: absolute;
      width: 100%;
      bottom: -25rpx;
      left: 0;
    }

    .left-line {
      position: absolute;
      left: 0;
      top: 40rpx;
      width: 3rpx;
      height: calc(100% - 80rpx);
      background-color: #C7A27C;
    }

    .right-line {
      position: absolute;
      right: 0;
      top: 40rpx;
      width: 3rpx;
      height: calc(100% - 80rpx);
      background-color: #C7A27C;
    }

    .title {
      position: relative;
      z-index: 1;
      font-family: "PingFangSC-Regular";
      font-size: 30rpx;
      color: #F55536;
      font-weight: 400;
      margin-bottom: 40rpx;
    }

    .desc {
      position: relative;
      z-index: 1;
      font-size: 42rpx;
      color: #333333;
      line-height: 63rpx;
      font-weight: 600;
      margin-bottom: 62rpx;
    }

    .button {
      position: relative;
      z-index: 1;
      text-align: center;
      border: 3rpx solid #C7A27C;
      background-color: #fff;
      border-radius: 12rpx;
      line-height: 96rpx;
      font-size: 36rpx;
      color: #333333;
      font-weight: 600;
      margin-bottom: 36rpx;

      &:nth-last-of-type(1) {
        margin-bottom: 0;
      }
    }

    .select-button {
      background-color: #F5E3D1;
    }
  }

  .footer {
    font-size: 30rpx;
    color: #C7A27C;
    font-weight: 600;
    padding: 0 18rpx;
    margin-top: 55rpx;
    display: flex;
    justify-content: space-between;

    .question {
      display: flex;
      align-items: center;
      padding: 33rpx 0;

      .left-arrow {
        width: 30rpx;
        height: 30rpx;
        margin-right: 12rpx;
      }

      .right-arrow {
        width: 30rpx;
        height: 30rpx;
        margin-left: 12rpx;
      }
    }

    .view-result {
      background: #F55536;
      border-radius: 12rpx;
      line-height: 96rpx;
      width: 74%;
      font-size: 36rpx;
      color: #FFFFFF;
      text-align: center;
      font-weight: 600;
    }
  }
}
</style>
